package com.pt.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pt.common.CommonResult;
import com.pt.entity.Request;
import com.pt.entity.User;
import com.pt.dto.response.RequestResponse;
import com.pt.service.RequestService;
import com.pt.service.UserService;
import com.pt.service.TorrentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;
import java.net.URLEncoder;

@Api(tags = "求种管理")
@RestController
@RequestMapping("/api/requests")
@RequiredArgsConstructor
public class RequestController {
    
    private final RequestService requestService;
    private final UserService userService;
    private final TorrentService torrentService;
    
    @ApiOperation("获取求种列表")
    @GetMapping
    public CommonResult<IPage<RequestResponse>> getRequests(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "20") Integer size,
            @ApiParam("分类ID") @RequestParam(required = false) Integer categoryId,
            @ApiParam("状态") @RequestParam(required = false) Integer status) {
        
        Page<RequestResponse> pageParam = new Page<>(page, size);
        IPage<RequestResponse> requests = requestService.getRequests(pageParam, categoryId, status);
        return CommonResult.success(requests);
    }
    
    @ApiOperation("获取求种详情")
    @GetMapping("/{requestId}")
    public CommonResult<RequestResponse> getRequestDetail(@ApiParam("求种ID") @PathVariable Long requestId) {
        RequestResponse request = requestService.getRequestById(requestId);
        if (request == null) {
            return CommonResult.error("求种不存在");
        }
        return CommonResult.success(request);
    }
    
    @ApiOperation("发布求种")
    @PostMapping
    @PreAuthorize("hasRole('USER')")
    public CommonResult<Request> createRequest(@RequestBody Request request, HttpServletRequest httpRequest) {
        User user = userService.getCurrentUser();
        
        // 检查用户魔力值是否足够
        if (user.getBonusPoints() < request.getRewardPoints()) {
            return CommonResult.error("魔力值不足");
        }
        
        request.setRequesterId(user.getId());
        request.setStatus(0); // 进行中
        request.setCreatedTime(LocalDateTime.now());
        
        Request createdRequest = requestService.createRequest(request);
        return CommonResult.success(createdRequest);
    }
    
    @ApiOperation("完成求种")
    @PutMapping("/{requestId}/fill")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<String> fillRequest(
            @ApiParam("求种ID") @PathVariable Long requestId,
            @RequestBody Map<String, Object> requestBody,
            HttpServletRequest httpRequest) {
        
        User user = userService.getCurrentUser();
        
        Long torrentId = Long.valueOf(requestBody.get("torrentId").toString());
        
        requestService.fillRequest(requestId, torrentId, user.getId());
        return CommonResult.success("求种已完成");
    }
    
    @ApiOperation("关闭求种")
    @PutMapping("/{requestId}/close")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<String> closeRequest(@ApiParam("求种ID") @PathVariable Long requestId, HttpServletRequest httpRequest) {
        User user = userService.getCurrentUser();
        
        requestService.closeRequest(requestId, user.getId());
        return CommonResult.success("求种已关闭");
    }

    @GetMapping("/{requestId}/download")
    @PreAuthorize("hasRole('USER')")
    @ApiOperation("下载求种对应的种子文件")
    public ResponseEntity<byte[]> downloadTorrent(
            @ApiParam("求种ID") @PathVariable Long requestId) {
        
        // 获取求种信息
        RequestResponse request = requestService.getRequestById(requestId);
        if (request == null || request.getFilledTorrentId() == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 获取当前用户
        User user = userService.getCurrentUser();
        if (user == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        try {
            // 下载种子文件
            byte[] torrentData = torrentService.downloadTorrent(request.getFilledTorrentId(), user.getPasskey());
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            String filename = URLEncoder.encode(request.getTorrentTitle() + ".torrent", "UTF-8");
            headers.setContentDispositionFormData("attachment", filename);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(torrentData);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
} 